// tslint:disable
import { Component, Input, OnInit } from '@angular/core';
import { Platform, ModalController, AlertController} from '@ionic/angular';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
@Component({
  selector: 'app-nearby-stores-list',
  templateUrl: './nearby-stores-list.component.html',
  styleUrls: ['./nearby-stores-list.component.scss'],
})
export class NearbyStoresListComponent implements OnInit {

  @Input() tagData;
  emptyDataHint = '暂无数据';
  loadDataToBottom = '已经到底了~';
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  // 筛选及页面数据参数
  params: any = { content: {} };
  eventListenerName = 'nearbyStoresListTag';
  setCustomBoxVisibility: any;
  ids: any;
  submitContent: any;
  constructor(
    private modalController: ModalController,
    private http: HttpService,
    private eventService: EventService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private alertController: AlertController,
  ) { }

  ngOnInit() {
    let that = this;
    if (this.tagData.data.submit !== undefined) {
      this.params = this.tagData.data.submit;
      this.pageSize = this.tagData.pageSize;
      this.pageTotal = this.tagData.pageTotal;
      this.showLoadMore = !this.tagData.data.moreButton &&
        this.tagData.data.submit &&
        this.pageTotal &&
        (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) &&
        this.tagData.asyncShow !== 'true';
    }


    const listenerName = this.tagData.name + 'AskForList';
    if (this.eventService.eventEmit.listenerCount(listenerName) > 0) {
      this.eventService.eventEmit.removeListener(listenerName);
    }
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshData(obj);
    });

    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    // 全选
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        that.tagData.data.data.forEach(element => {
          element.checked = true;
        });
      } else {
        that.tagData.data.data.forEach(element => {
          element.checked = false;
        }); 
      }
    });

    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      const ids = [];
      this.tagData.data.data.forEach((element) => {
        if (element.checked) {
          ids.push(element.id);
        }
      });
      if (ids.length === 0 && !res.noNeedChoose) {
        this.ids = '';
        return;
      }
      this.ids = ids.join(',');

      if (res.target) {
        this.showModal(res);
      } else {
        // submit
        this.presentAlertWithMsgBtn(res);
      }

    });


    if (this.tagData.data && this.tagData.data && this.tagData.data.data) {
      if (this.tagData.data.data[0]
        && this.tagData.data.data[0].enableSetCustomBoxVisibility !== undefined
        && this.tagData.data.data[0].enableSetCustomBoxVisibility === 'true') {
        this.eventService.eventEmit.on('setCustomBoxVisibility', (obj) => {
          this.setCustomBoxVisibility = obj;
        });
      }

      if (this.tagData.data.data[0]
        && this.tagData.data.data[0].setCheckBoxVisibility !== undefined
      ) {
        this.setCustomBoxVisibility = this.tagData.data.setCheckBoxVisibility;
      }

      if (this.appGlobalService.setCustomBoxVisibility !== undefined) {
        this.setCustomBoxVisibility = this.appGlobalService.setCustomBoxVisibility;
      }
    }
  }

  refreshData(param, event?) {
    const that = this;
    if (param === undefined) {
      return;
    }
    if (this.params === undefined) {
      this.params = { content: {} };
    }
    this.params.content = param;
    this.params['sessionId'] = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    if (param) {
      Object.assign(this.params.content, param);
    }
    // 请求获取新数据
    this.http.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadMoreData(event) {
    if (!this.params) {
      this.params = { content: {} };
      this.params = this.tagData.data.submit.content;
    }
    this.pageNo = this.pageNo + 1;// // 参数
    this.params.content.pageNo = this.pageNo;
    this.params.id = this.tagData.data.submit.id;
    this.params.sessionId = localStorage.getItem("sessionId");

    this.http.post(
      "application/submit",
      this.params,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          this.tagData.data.submit = res.data.submit;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.tagData.data.data.push(item);
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }

  openPage(item) {
    this.pageModalService.openPage(item.link);
  }

  iconClick(item) {
    const that = this;
    if (item.link && item.modelType === undefined) {
      if (item.link.type === 'page') {
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      } else if (item.link.type === 'model') {
        item.link.modalCss = 'auto-modal';
        this.pageModalService.openPage(item.link, '', result => {
          if (result) {
          }
        });

      }
    } else if (item.modelType === "iconSubmit") {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {
        this.http.gotoChat(item);
      }
    }
  }

  choose(item) {
    item.checked = !item.checked;
    let all = true;
    this.tagData.data.data.forEach(element => {
      if (!element.checked) {
        all = false;
        return;
      }
    });
    this.eventService.eventEmit.emit('recommendAllResult', all);
  }

  showModal(link) {
    const that = this;

    link.params.id = this.ids;

    this.pageModalService.openPage(link, '', result => {
      if (result) {
        console.log('test' + JSON.stringify(result));
      }
    });

  }

    async presentAlertWithMsgBtn(submit) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            if (submit.content.listKey) {
              submit.content[submit.content.listKey] = this.ids;
            } else if (submit.content.newListKeyName) {
              submit.content = {};
              let tempContent;
              if (this.submitContent) {
                tempContent = Object.assign(submit.content, this.submitContent);
              }
              submit.content['id'] = this.ids;
            } else {
              submit.content.id = this.ids;
            }
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.http.post("application/submit", params, res => {
              if (res.success) {
                if (submit && submit.content.updateType && submit.content.updateType === 'deleteItem') {
                  this.tagData.data.data = this.tagData.data.data.filter((item)=> item.checked !== true);
                } else {
                  that.appGlobalService.reloadCurrentPage();
                }
                this.eventService.eventEmit.emit('submitRes', JSON.stringify({ res, submit }));
              }
              if (res.message && res.message.length > 0) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
              }

            });
          }
        }
      ]
    });
    await alert.present();
  }
}
